package com.wms_backend.utils;

import com.alibaba.fastjson.JSON;
import com.wms_backend.dao.VehicleDao;
import com.wms_backend.entity.Vehicle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    private static final ConcurrentMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Autowired
    private VehicleDao vehicleDao;

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("Received: " + payload);
        session.sendMessage(new TextMessage("Hello, " + payload + "!"));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.put(session.getId(), session);
        List<Vehicle> vehicleList= vehicleDao.findAll();
        String jsonString = JSON.toJSONString(vehicleList);
        session.sendMessage(new TextMessage(jsonString));
        System.out.println("Connected: " + session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session.getId());
        System.out.println("Disconnected: " + session.getId());
    }

    // 主动向客户端发送消息
    public void sendMessageToAll() {
        List<Vehicle> vehicleList= vehicleDao.findAll();
        String jsonString = JSON.toJSONString(vehicleList);
        TextMessage textMessage = new TextMessage(jsonString);
        sessions.forEach((id, session) -> {
            try {
                if (session.isOpen()) {
                    session.sendMessage(textMessage);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
